import Consul from 'consul';
import axios from 'axios';
import * as util from "util";
async function main() {
    try {
        // Create Consul client
        const consul = new Consul({
            host: '95.169.25.181',
            port: '8500'
        });
        const serviceName1 = 'your-service';
        // Query Consul for service nodes
        const servicePassingNodes =await consul.health.service({
                service: serviceName1,
                passing: true
            })
        console.log("======================[servicePassingNodes]======================")
        console.log(util.inspect(servicePassingNodes, false,null,true));

        // console.log(util.inspect(servicePassingNodes, false, null, true));
        if (servicePassingNodes instanceof Array) {
            // 选择一个服务实例（这里简单地选择第一个实例）
            const selectedInstance = servicePassingNodes[0];
            if (selectedInstance) {
                // Make a request to the selected service
                const serviceUrl = `http://${selectedInstance.Service.Address}:${selectedInstance.Service.Port}`;
                const response = await axios.get(`${serviceUrl}/`);

                console.log('Service response:', response.data);
            } else {
                console.error('No healthy service available for', serviceName1);
            }
        }

    } catch (error) {
        if (error instanceof Error) {
            console.error('Error:', error.message);
        }
    }
}

main()